package com.turing.pre.processor.file.processor;

import cn.hutool.core.img.Img;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * 图片处理工具类
 */
public class ImageUtils {
    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(ImageUtils.class);

    /**
     * 	判断图片是否为tiff
     *  @param b
     *  @return
     */
    public static boolean checkImageType(byte[] b) {
        try {
            // 	判断是否为tiff格式
            if((b[0] & 0xFF) == 0x49 && (b[1] & 0xFF)==0x49 &&  (b[2] & 0xFF)==0x2A){
                return true;
            }else {
                return false;
            }
        }catch(Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 	将tiff图片转化为jpg
     *  @param in	原图片文件流
     */
    public static ByteArrayOutputStream tiffToJpg(InputStream in) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            BufferedImage bufferegImage= ImageIO.read(in);
            // 正常情况下，直接使用图片转换，得到的jpg图片会有色彩失真的情况
            // ImageIO.write(bufferegImage,"jpg",out);
            // 此处使用hutool的图片处理工具，将tif图片转换为jpg，可完美解决图片失真的问题
            Img.from(bufferegImage).write(out);
        }catch(IOException e) {
            e.printStackTrace();
        }finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    LOG.error(e.getMessage(), e);
                }
            }
        }
        return out;
    }

    public static void tiffToJpg(String oldPath,String newPath) {
        try {
            BufferedImage bufferegImage=ImageIO.read(new File(oldPath));
            Thumbnails.of(bufferegImage).scale(1f).toFile(newPath);

        }catch(IOException e) {
            e.printStackTrace();
        }
    }

}

